#!/bin/bash

# nginx 管理脚本
# 用于启动、停止、重启和检查 nginx 状态

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查 nginx 是否运行
check_nginx_status() {
    if pgrep -f "nginx.*master" > /dev/null; then
        return 0
    else
        return 1
    fi
}

# 显示 nginx 状态
show_status() {
    echo "=== nginx 状态检查 ==="
    
    if check_nginx_status; then
        log_success "nginx 正在运行"
        echo ""
        echo "nginx 进程:"
        ps aux | grep nginx | grep -v grep
        echo ""
        echo "nginx 端口监听:"
        lsof -i :80 -i :443 | grep nginx || echo "未找到 nginx 端口监听"
    else
        log_error "nginx 未运行"
    fi
    
    echo ""
    echo "brew services 状态:"
    brew services list | grep nginx
    echo ""
}

# 启动 nginx
start_nginx() {
    echo "=== 启动 nginx ==="
    
    if check_nginx_status; then
        log_warning "nginx 已经在运行"
        return 0
    fi
    
    # 检查配置文件
    log_info "检查 nginx 配置..."
    if nginx -t; then
        log_success "配置文件语法正确"
    else
        log_error "配置文件有错误"
        return 1
    fi
    
    # 启动 nginx
    log_info "启动 nginx..."
    nginx
    
    if check_nginx_status; then
        log_success "nginx 启动成功"
    else
        log_error "nginx 启动失败"
        return 1
    fi
}

# 停止 nginx
stop_nginx() {
    echo "=== 停止 nginx ==="
    
    if ! check_nginx_status; then
        log_warning "nginx 未运行"
        return 0
    fi
    
    log_info "停止 nginx..."
    nginx -s quit
    
    # 等待进程结束
    sleep 2
    
    if check_nginx_status; then
        log_error "nginx 停止失败，尝试强制停止..."
        pkill -f nginx
        sleep 1
    else
        log_success "nginx 停止成功"
    fi
}

# 重启 nginx
restart_nginx() {
    echo "=== 重启 nginx ==="
    
    log_info "停止 nginx..."
    stop_nginx
    
    log_info "启动 nginx..."
    start_nginx
}

# 重新加载配置
reload_nginx() {
    echo "=== 重新加载 nginx 配置 ==="
    
    if ! check_nginx_status; then
        log_error "nginx 未运行，无法重新加载配置"
        return 1
    fi
    
    # 检查配置文件
    log_info "检查 nginx 配置..."
    if nginx -t; then
        log_success "配置文件语法正确"
    else
        log_error "配置文件有错误"
        return 1
    fi
    
    # 重新加载配置
    log_info "重新加载 nginx 配置..."
    nginx -s reload
    
    log_success "nginx 配置重新加载成功"
}

# 测试 nginx 连接
test_nginx() {
    echo "=== 测试 nginx 连接 ==="
    
    if ! check_nginx_status; then
        log_error "nginx 未运行"
        return 1
    fi
    
    log_info "测试 HTTP 连接..."
    if curl -s -I http://localhost > /dev/null; then
        log_success "HTTP 连接正常"
    else
        log_error "HTTP 连接失败"
    fi
    
    log_info "测试 HTTPS 连接..."
    if curl -k -s -I https://192.168.137.122/api/auth/test > /dev/null; then
        log_success "HTTPS 连接正常"
    else
        log_error "HTTPS 连接失败"
    fi
    
    log_info "测试 API 连接..."
    if curl -k -s https://192.168.137.122/api/auth/test | grep -q "success"; then
        log_success "API 连接正常"
    else
        log_error "API 连接失败"
    fi
}

# 管理 SSL 证书
manage_cert() {
    echo "=== SSL 证书管理 ==="
    
    CERT_FILE="nginx/ssl/smartinput.crt"
    
    if [ ! -f "$CERT_FILE" ]; then
        log_error "证书文件不存在: $CERT_FILE"
        return 1
    fi
    
    log_success "找到证书文件: $CERT_FILE"
    
    # 检查证书是否已导入
    log_info "检查证书是否已导入到登录钥匙串..."
    if security find-certificate -c "192.168.137.122" ~/Library/Keychains/login.keychain-db > /dev/null 2>&1; then
        log_success "证书已存在于登录钥匙串"
    else
        log_warning "证书未在登录钥匙串中找到，正在导入..."
        if security import "$CERT_FILE" -k ~/Library/Keychains/login.keychain-db; then
            log_success "证书已导入到登录钥匙串"
        else
            log_error "证书导入失败"
            return 1
        fi
    fi
    
    # 检查证书是否已信任
    log_info "检查证书信任状态..."
    if security find-trust-settings -d "192.168.137.122" ~/Library/Keychains/login.keychain-db > /dev/null 2>&1; then
        log_success "证书已设置为信任状态"
    else
        log_warning "证书未设置为信任状态，正在设置..."
        if security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/login.keychain-db "$CERT_FILE"; then
            log_success "证书已设置为信任状态"
        else
            log_error "设置证书信任状态失败"
            return 1
        fi
    fi
    
    # 检查系统钥匙串
    log_info "检查系统钥匙串中的证书..."
    if security find-certificate -c "192.168.137.122" /Library/Keychains/System.keychain > /dev/null 2>&1; then
        log_success "证书已存在于系统钥匙串"
    else
        log_warning "证书未在系统钥匙串中找到"
        log_info "要导入到系统钥匙串，请运行: sudo security import $CERT_FILE -k /Library/Keychains/System.keychain"
    fi
    
    # 测试证书连接
    log_info "测试证书连接..."
    if curl -s -I https://192.168.137.122/api/auth/test > /dev/null 2>&1; then
        log_success "HTTPS 连接正常（证书已信任）"
    else
        log_warning "HTTPS 连接仍有问题，可能需要重启浏览器"
    fi
    
    echo ""
    log_info "证书管理完成。如果浏览器仍显示证书警告，请："
    echo "1. 重启浏览器"
    echo "2. 清除浏览器缓存"
    echo "3. 重新访问 https://192.168.137.122"
}

# 显示帮助信息
show_help() {
    echo "nginx 管理脚本"
    echo ""
    echo "用法: $0 [命令]"
    echo ""
    echo "命令:"
    echo "  status    显示 nginx 状态"
    echo "  start     启动 nginx"
    echo "  stop      停止 nginx"
    echo "  restart   重启 nginx"
    echo "  reload    重新加载配置"
    echo "  test      测试 nginx 连接"
    echo "  cert      管理 SSL 证书（导入并信任）"
    echo "  help      显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 status"
    echo "  $0 start"
    echo "  $0 cert"
    echo "  $0 restart"
}

# 主函数
main() {
    case "${1:-help}" in
        status)
            show_status
            ;;
        start)
            start_nginx
            ;;
        stop)
            stop_nginx
            ;;
        restart)
            restart_nginx
            ;;
        reload)
            reload_nginx
            ;;
        test)
            test_nginx
            ;;
        cert)
            manage_cert
            ;;
        help|*)
            show_help
            ;;
    esac
}

# 运行主函数
main "$@" 